package mysql

import (
	"gorm.io/gorm"
)

type House struct {
	gorm.Model
	Title   string  `gorm:"type:varchar(30);comment:房源名称"`
	Price   float64 `gorm:"type:decimal(10,2);comment:房源价格"`
	Address string  `gorm:"type:varchar(50);comment:房源地址"`
	MiaJi   float64 `gorm:"type:decimal(10,2);comment:房源面积"`
	Avatar  string  `gorm:"type:varchar(255);comment:房源图片"`
	Mobile  string  `gorm:"type:char(18);comment:手机号"`
	MiaShu  string  `gorm:"type:char(18);comment:描述"`
}

// 手机号查询信息
func (h *House) FindByMobileUserInfo(mobile string) error {
	return DB.Where("mobile = ?", mobile).Find(&h).Error
}

// 房源列表分页查询 房源地区查询
func (h *House) HouseFindListByTitle(title, address string, page, size int) ([]*House, error) {
	var sel []*House
	err = DB.Where("title like ?", "%"+title+"%").Where(
		"address like ?", "%"+address+"%").Order("price desc").Scopes(Paginate(page, size)).Find(&sel).Error
	return sel, err
}

// 房源地区查询
func (h *House) HouseFindListByAddress(address string) error {
	return DB.Where("address like ?", "%"+address+"%").Find(&h).Error

}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
